package reno.market.mainmarket.warframemarket.service;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reno.market.mainmarket.common.HttpGetTool;
import reno.market.mainmarket.common.StringContent;
import reno.market.mainmarket.warframemarket.dao.WarframeMarketDao;
import reno.market.mainmarket.warframemarket.entity.WarframemarketEO;
import reno.market.mainmarket.warframemarket.entity.WarframemarketkeywordEO;
import reno.market.mainmarket.warframemarket.mo.Orders;
import reno.market.mainmarket.common.ResponseMO;
import reno.market.mainmarket.warframemarket.mo.TradeMO;
import reno.market.mainmarket.warframemarket.mo.WarframeMarketMO;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

@Service
public class WarframeMarketService {

    @Autowired
    WarframeMarketDao warframeMarketDao;

    /**
     * 对传入物品中文名做转义
     * 并从库中取出物品信息
     *
     * @param queryStr 待查询物品名
     * @return Map<String                                                                                                                               ,                                                                                                                               String>
     * "item_en"    物品英文名
     * "item_cn"    物品中文名
     * "item_url"   物品wm页面Url
     * "other"      物品其余可查询配件及DC值
     * @Author RenoSirp
     */
    public Map<String, String> translateInfo(String queryStr) {
        //提取简称部分
        String keyword = queryStr.substring(0, !queryStr.contains(" ") ? queryStr.length() : queryStr.indexOf(" "));
        //查询物品全名和相关物品信息
        List<WarframemarketkeywordEO> warframemarketkeywordEOList = warframeMarketDao.queryKeywordFull(keyword);
        //如果取得物品全名，则置入keyword_full
        String keyword_full;
        if (warframemarketkeywordEOList.size() > 0) {
            keyword_full = warframemarketkeywordEOList.get(0).getItemEn();
            //替换简称为全名
            queryStr = queryStr.replace(keyword, keyword_full);
        }
        //替换空格为%做模糊匹配用
        List<WarframemarketEO> warframemarketEOList = warframeMarketDao.queryItemInfo(queryStr.replace(" ", "%"));
        Map<String, String> result = new HashMap<>();
        //对数据库内对象做整理，取得所需信息
        if (warframemarketEOList.size() > 0) {
            result.put("item_en", warframemarketEOList.get(0).getItemEn());
            result.put("item_cn", warframemarketEOList.get(0).getItemCn());
            result.put("item_url", warframemarketEOList.get(0).getUrl());
            StringBuilder other = new StringBuilder("您还可以查询以下部件：\n");
            for (WarframemarketEO eachEO : warframemarketEOList) {
                if (null != eachEO.getDucats()) {
                    other.append(eachEO.getItemCn() + " DC " + eachEO.getDucats() + " \n");
                } else {
                    other.append(eachEO.getItemCn() + " \n");
                }
            }
            result.put("other", other.toString());
        } /*else {
            //查询到空对象时
            //不做操作，返回空map
        }*/
        return result;
    }

    /**
     * 根据传入的物品信息从warframe.market获取交易信息
     * 并对获取到的交易信息做排序和整理
     *
     * @param itemInfo 物品信息
     */
    public Map<String, Vector<WarframeMarketMO>> getTradeInfo(Map<String, String> itemInfo) {
        Map<String, Vector<WarframeMarketMO>> result = null;
        String item_en = itemInfo.get("item_en");
        String item_cn = itemInfo.get("item_cn");
        String item_url = itemInfo.get("item_url");
        if (item_url != null || item_url.length() > 0) {
            String tradeurl = "https://api.warframe.market/v1/items/TARGET/orders?include=item";
            String jsonString = HttpGetTool.getResult(tradeurl.replace("TARGET", item_url));
            TradeMO tradeMO = JSON.parseObject(jsonString, TradeMO.class);
            if (tradeMO != null) {
                List<Orders> ordersList = tradeMO.getPayload().getOrders();
                Vector<WarframeMarketMO> sellMarketMOs = new Vector<>();
                Vector<WarframeMarketMO> buyMarketMOs = new Vector<>();
                for (Orders eachOrders : ordersList) {
                    WarframeMarketMO warframeMarketMO = new WarframeMarketMO();
                    warframeMarketMO.setUser(eachOrders.getUser());
                    warframeMarketMO.setOrderType(eachOrders.getOrderType());
                    warframeMarketMO.setQuantity(eachOrders.getQuantity());
                    warframeMarketMO.setModRank(eachOrders.getModRank());
                    warframeMarketMO.setPaltinum(eachOrders.getPlatinum());
                    if (warframeMarketMO.getUser().getStatus().equals(StringContent.INGAME)) {
                        if (warframeMarketMO.getOrderType().equals(StringContent.SELL)) {
                            sellMarketMOs.add(warframeMarketMO);
                        } else if (warframeMarketMO.getOrderType().equals(StringContent.BUY)) {
                            buyMarketMOs.add(warframeMarketMO);
                        }
                    }
                }
                sellMarketMOs.sort(this::compareSell);
                buyMarketMOs.sort(this::compareBuy);
                sellMarketMOs.setSize(5 < sellMarketMOs.size() ? 5 : sellMarketMOs.size());
                buyMarketMOs.setSize(5 < buyMarketMOs.size() ? 5 : buyMarketMOs.size());
                result = new HashMap<>();
                result.put(StringContent.BUY, buyMarketMOs);
                result.put(StringContent.SELL, sellMarketMOs);
            }
        }
        return result;
    }

    /**
     * 将wm获取到的交易信息和数据库中取出的物品信息
     * 构建成ResponseMO
     *
     * @param tradeInfo 交易信息
     * @param itemInfo  物品信息
     * @return
     */
    public ResponseMO buildResponse(Map<String, Vector<WarframeMarketMO>> tradeInfo, Map<String, String> itemInfo) {
        if (tradeInfo==null){
            ResponseMO responseMO =  new ResponseMO();
            responseMO.setResponseString0("warframe.market链接出现问题，请稍后重试。");
            return responseMO;
        }
        Vector<WarframeMarketMO> sellMarketMOs = tradeInfo.get(StringContent.SELL);
        Vector<WarframeMarketMO> buyMarketMOs = tradeInfo.get(StringContent.BUY);
        ResponseMO responseMO = new ResponseMO();
        StringBuilder msgSell = new StringBuilder("指挥官，WM查询结果如下：\n物品名：ITEM 【出售】\n");
        for (WarframeMarketMO eachMO : sellMarketMOs) {
            String str;
            if (eachMO.getModRank() == null) {
                str = eachMO.getPaltinum() + "P 每个,出售 " + eachMO.getQuantity() + " 个 卖家名：[" + eachMO.getUser().getIngameName() + "]\n";
            } else {
                str = eachMO.getPaltinum() + "P 每个,等级 " + eachMO.getModRank() + " ,共售 " + eachMO.getQuantity() + " 个 卖家名：[" + eachMO.getUser().getIngameName() + "]\n";
            }
            msgSell.append(str);
        }
        msgSell.append("回复1查看私聊交易命令\n回复2查看买家\n回复3查看其余部件及杜卡德金币价格");
        StringBuilder msgBuy = new StringBuilder("指挥官，WM查询结果如下：\n物品名：ITEM 【求购】\n");
        for (WarframeMarketMO eachMO : buyMarketMOs) {
            String str;
            if (eachMO.getModRank() == null) {
                str = eachMO.getPaltinum() + "P 每个,求购 " + eachMO.getQuantity() + " 个 买家名：[" + eachMO.getUser().getIngameName() + "]\n";
            } else {
                str = eachMO.getPaltinum() + "P 每个,等级 " + eachMO.getModRank() + " ,共收 " + eachMO.getQuantity() + " 个 买家名：[" + eachMO.getUser().getIngameName() + "]\n";
            }
            msgBuy.append(str);
        }
        responseMO.setResponseString0(msgSell.toString().replace("ITEM", itemInfo.get("item_cn")));
        String psg = "私聊交易指令：[/w 玩家名 hi,i wtb ITEM for 价格 P from warframe.market ]\n请复制[]中内容，并替换玩家名为交易对象名，价格为交易价格，在游戏内聊天框粘贴发送即可开始交易。";
        responseMO.setResponseString1(psg.replace("ITEM", itemInfo.get("item_en")));
        responseMO.setResponseString2(msgBuy.toString().replace("ITEM", itemInfo.get("item_cn")));
        responseMO.setResponseString3(itemInfo.get("other"));
        return responseMO;
    }

    /**
     * 卖家排序
     * 升序
     *
     * @param o1
     * @param o2
     * @return
     */
    private int compareSell(WarframeMarketMO o1, WarframeMarketMO o2) {
        if (o1.getPaltinum() > o2.getPaltinum()) {
            return 1;
        } else if (o1.getPaltinum() < o2.getPaltinum()) {
            return -1;
        }
        return 0;
    }

    /**
     * 买家排序
     * 降序
     *
     * @param o1
     * @param o2
     * @return
     */
    private int compareBuy(WarframeMarketMO o1, WarframeMarketMO o2) {
        if (o1.getPaltinum() > o2.getPaltinum()) {
            return -1;
        } else if (o1.getPaltinum() < o2.getPaltinum()) {
            return 1;
        }
        return 0;
    }
}
